package com.github.binarywang.demo.wx.mp.controller;

import com.github.binarywang.demo.wx.mp.handler.SubscribeHandler;
import com.github.binarywang.demo.wx.mp.utils.StorageUtils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;

import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.img.ImgUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.extra.qrcode.QrCodeUtil;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpQrCodeTicket;

@RestController
@Slf4j
@RequestMapping("/wx/qrcode/{appId}")
public class QrcodeController {

    @Autowired
    private WxMpService wxMpService;

    /**
     * 创建公众号二维码
     * 关注之后,可以在 {@link SubscribeHandler} 中,获取到 shangHuId ,把关注客户的openId和商户绑定.
     *
     * 生成二维码:
     * http://localhost:8080/wx/qrcode/wxa4f880b9a8ed4e2c/create?sceneStr=%7B%22url%22%3A%22http%3A%2F%2Fzd4n4z.natappfree.cc%2Ftest%2Fhello%3Fname%3Danxiaole%26state%3D250%22%2C%22appId%22%3A%22wxa4f880b9a8ed4e2c%22%7D
     *
     * todo:那种生成一个url,打开这个url时,需要先关注公众号,然后需要授权用户openId的接口是什么?
     *  传入场景字符串sceneStr
     *
     * @param appId
     * @param sceneStr 场景字符串
     * @return
     */
    @RequestMapping(value = "/create", produces = MediaType.IMAGE_PNG_VALUE)
    public Object getAccessToken(@PathVariable String appId, String sceneStr, HttpServletResponse response) {
        String key = UUID.fastUUID().toString(true);
        StorageUtils.put(key, sceneStr);
        try {
            WxMpQrCodeTicket wxMpQrCodeTicket = wxMpService.switchoverTo(appId).getQrcodeService().qrCodeCreateLastTicket(key);
            // 获取的二维码ticket，凭借此 ticket 可以在有效时间内换取二维码。
            String ticket = wxMpQrCodeTicket.getTicket();
            QrCodeUtil.generate(wxMpQrCodeTicket.getUrl(), 500, 500, ImgUtil.IMAGE_TYPE_PNG, response.getOutputStream());
            return null;
        } catch (WxErrorException | IOException e) {
            e.printStackTrace();
            return "ERROR";
        }
    }
}
